<template>
  <view class="settings-page" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @click="goBack">
        <text class="i-fa-solid:arrow-left"></text>
      </view>
      <view class="navbar-title">设置</view>
      <view class="navbar-right"></view>
    </view>

    <!-- 设置内容 -->
    <scroll-view scroll-y class="settings-container">
      <view class="p-4">
        <!-- 测试数据管理分组 -->
        <view class="settings-group">
          <view class="settings-group-title">测试数据管理</view>
          
          <!-- 测试数据管理 -->
          <view class="settings-item" @click="navigateToTestDataPage">
            <view class="settings-item-left">
              <text class="i-fa-solid:flask text-green-500"></text>
              <text class="settings-item-label">测试数据管理</text>
            </view>
            <view class="settings-item-right">
              <text class="i-fa-solid:chevron-right text-gray-400"></text>
            </view>
          </view>
          
          <!-- 生成测试数据 -->
          <view class="settings-item" @click="handleGenerateTestData">
            <view class="settings-item-left">
              <text class="i-fa-solid:database text-indigo-500"></text>
              <text class="settings-item-label">生成测试数据</text>
            </view>
            <view class="settings-item-right">
              <text class="i-fa-solid:chevron-right text-gray-400"></text>
            </view>
          </view>
          
          <!-- 清空测试数据 -->
          <view class="settings-item" @click="handleClearTestData">
            <view class="settings-item-left">
              <text class="i-fa-solid:eraser text-orange-500"></text>
              <text class="settings-item-label">清空测试数据</text>
            </view>
            <view class="settings-item-right">
              <text class="i-fa-solid:chevron-right text-gray-400"></text>
            </view>
          </view>
          
          <!-- 数据库测试 -->
          <view class="settings-item" @click="navigateToDatabaseTest">
            <view class="settings-item-left">
              <text class="i-fa-solid:database text-blue-500"></text>
              <text class="settings-item-label">数据库测试</text>
            </view>
            <view class="settings-item-right">
              <text class="i-fa-solid:chevron-right text-gray-400"></text>
            </view>
          </view>
        </view>
        
        <!-- 数据管理分组 -->
        <view class="settings-group">
          <view class="settings-group-title">数据管理</view>
          
          <!-- 数据备份 -->
          <view class="settings-item" @click="handleDataBackup">
            <view class="settings-item-left">
              <text class="i-fa-solid:save text-blue-500"></text>
              <text class="settings-item-label">数据备份</text>
            </view>
            <view class="settings-item-right">
              <text class="i-fa-solid:chevron-right text-gray-400"></text>
            </view>
          </view>
          
          <!-- 数据恢复 -->
          <view class="settings-item" @click="handleDataRestore">
            <view class="settings-item-left">
              <text class="i-fa-solid:undo text-green-500"></text>
              <text class="settings-item-label">数据恢复</text>
            </view>
            <view class="settings-item-right">
              <text class="i-fa-solid:chevron-right text-gray-400"></text>
            </view>
          </view>
          
          <!-- 数据导出 -->
          <view class="settings-item" @click="handleDataExport">
            <view class="settings-item-left">
              <text class="i-fa-solid:file-export text-purple-500"></text>
              <text class="settings-item-label">数据导出</text>
            </view>
            <view class="settings-item-right">
              <text class="i-fa-solid:chevron-right text-gray-400"></text>
            </view>
          </view>
          
          <!-- 数据导入 -->
          <view class="settings-item" @click="handleDataImport">
            <view class="settings-item-left">
              <text class="i-fa-solid:file-import text-orange-500"></text>
              <text class="settings-item-label">数据导入</text>
            </view>
            <view class="settings-item-right">
              <text class="i-fa-solid:chevron-right text-gray-400"></text>
            </view>
          </view>

          <!-- 清空数据 -->
          <view class="settings-item" @click="handleClearData">
            <view class="settings-item-left">
              <text class="i-fa-solid:trash-alt text-red-500"></text>
              <text class="settings-item-label">清空数据</text>
            </view>
            <view class="settings-item-right">
              <text class="i-fa-solid:chevron-right text-gray-400"></text>
            </view>
          </view>
        </view>
        
        <!-- 应用设置分组 -->
        <view class="settings-group">
          <view class="settings-group-title">应用设置</view>
          
          <!-- 主题设置 -->
          <view class="settings-item">
            <view class="settings-item-left">
              <text class="i-fa-solid:palette text-indigo-500"></text>
              <text class="settings-item-label">主题设置</text>
            </view>
            <view class="settings-item-right">
              <picker mode="selector" :range="themes" @change="onThemeChange">
                <view class="picker-text">{{ themes[currentTheme] }}</view>
              </picker>
            </view>
          </view>
          
          <!-- 提醒设置 -->
          <view class="settings-item">
            <view class="settings-item-left">
              <text class="i-fa-solid:bell text-yellow-500"></text>
              <text class="settings-item-label">任务提醒</text>
            </view>
            <view class="settings-item-right">
              <switch :checked="remindersEnabled" @change="toggleReminders" color="#007aff" />
            </view>
          </view>
        </view>
        
        <!-- 关于分组 -->
        <view class="settings-group">
          <view class="settings-group-title">关于</view>
          
          <!-- 版本信息 -->
          <view class="settings-item">
            <view class="settings-item-left">
              <text class="i-fa-solid:info-circle text-blue-500"></text>
              <text class="settings-item-label">版本信息</text>
            </view>
            <view class="settings-item-right">
              <text class="text-gray-500">v1.0.0</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 加载中遮罩 -->
    <view class="loading-overlay" v-if="loading">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">{{ loadingText }}</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'SettingsPage',
})

import { backupService } from '@/services/backup-service'
import { dataGenerator } from '@/services/data-generator'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 主题设置
const themes = ['跟随系统', '浅色模式', '深色模式']
const currentTheme = ref(0)

// 提醒设置
const remindersEnabled = ref(true)

// 加载状态
const loading = ref(false)
const loadingText = ref('加载中...')

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 切换主题
const onThemeChange = (e: any) => {
  currentTheme.value = e.detail.value
  // 这里实现主题切换逻辑
}

// 切换提醒设置
const toggleReminders = (e: any) => {
  remindersEnabled.value = e.detail.value
  // 这里实现提醒设置的保存逻辑
}

// 生成测试数据
const handleGenerateTestData = async () => {
  uni.showModal({
    title: '生成测试数据',
    content: '请选择要生成的任务数量',
    editable: true,
    placeholderText: '请输入5-20之间的数字',
    success: async (res) => {
      if (res.confirm) {
        let count = parseInt(res.content || '10')
        
        // 验证输入
        if (isNaN(count) || count < 5) {
          count = 5
        } else if (count > 20) {
          count = 20
        }
        
        try {
          showLoading(`正在生成${count}条测试数据...`)
          const success = await dataGenerator.generateTasks(count)
          hideLoading()
          
          if (success) {
            uni.showToast({
              title: `成功生成${count}条测试数据`,
              icon: 'success'
            })
          } else {
            throw new Error('生成测试数据失败')
          }
        } catch (error) {
          hideLoading()
          uni.showModal({
            title: '生成失败',
            content: error.message || '生成测试数据过程中发生错误',
            showCancel: false
          })
        }
      }
    }
  })
}

// 清空测试数据
const handleClearTestData = async () => {
  uni.showModal({
    title: '警告',
    content: '确定要清空所有测试数据吗？此操作不可恢复！',
    confirmColor: '#FF0000',
    success: async (res) => {
      if (res.confirm) {
        try {
          showLoading('正在清空测试数据...')
          const success = await dataGenerator.clearAllTestData()
          hideLoading()
          
          if (success) {
            uni.showToast({
              title: '已清空所有测试数据',
              icon: 'success'
            })
          } else {
            throw new Error('清空测试数据失败')
          }
        } catch (error) {
          hideLoading()
          uni.showModal({
            title: '操作失败',
            content: error.message || '清空数据过程中发生错误',
            showCancel: false
          })
        }
      }
    }
  })
}

// 数据备份
const handleDataBackup = async () => {
  try {
    // 检查平台
    // #ifdef APP-PLUS
    showLoading('正在备份数据...')
    
    // 执行备份
    const filePath = await backupService.saveBackupToFile()
    
    hideLoading()
    uni.showModal({
      title: '备份成功',
      content: `数据已备份至: ${filePath}`,
      showCancel: false
    })
    // #endif
    
    // #ifndef APP-PLUS
    uni.showModal({
      title: '提示',
      content: '备份功能仅在APP环境下可用',
      showCancel: false
    })
    // #endif
  } catch (error) {
    hideLoading()
    uni.showModal({
      title: '备份失败',
      content: error.message || '备份过程中发生错误',
      showCancel: false
    })
  }
}

// 数据恢复
const handleDataRestore = async () => {
  try {
    // 检查平台
    // #ifdef APP-PLUS
    showLoading('获取备份文件列表...')
    
    // 获取备份文件列表
    const backupFiles = await backupService.getBackupFiles()
    
    hideLoading()
    
    if (backupFiles.length === 0) {
      uni.showModal({
        title: '提示',
        content: '没有找到备份文件',
        showCancel: false
      })
      return
    }
    
    // 显示备份文件列表供用户选择
    uni.showActionSheet({
      itemList: backupFiles.map(file => `${file.date} (${file.name})`),
      success: async (res) => {
        const selectedFile = backupFiles[res.tapIndex]
        if (selectedFile) {
          // 确认恢复
          uni.showModal({
            title: '确认恢复',
            content: `确定要从"${selectedFile.date}"的备份中恢复数据吗？这将覆盖当前所有数据。`,
            success: async (res) => {
              if (res.confirm) {
                // 执行恢复
                showLoading('正在恢复数据...')
                await backupService.restoreFromFile(selectedFile.path)
                hideLoading()
                
                uni.showToast({
                  title: '恢复成功',
                  icon: 'success',
                  duration: 2000
                })
              }
            }
          })
        }
      }
    })
    // #endif
    
    // #ifndef APP-PLUS
    uni.showModal({
      title: '提示',
      content: '恢复功能仅在APP环境下可用',
      showCancel: false
    })
    // #endif
  } catch (error) {
    hideLoading()
    uni.showModal({
      title: '恢复失败',
      content: error.message || '恢复过程中发生错误',
      showCancel: false
    })
  }
}

// 数据导出
const handleDataExport = async () => {
  try {
    showLoading('正在导出数据...')
    
    // 导出为JSON字符串
    const jsonData = await backupService.exportBackupAsJson()
    
    // #ifdef H5
    // 在H5环境下，可以创建下载链接
    const blob = new Blob([jsonData], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    const fileName = `task_backup_${formatDate(new Date())}.json`
    a.href = url
    a.download = fileName
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    
    hideLoading()
    uni.showToast({
      title: '导出成功',
      icon: 'success'
    })
    // #endif
    
    // #ifndef H5
    // 在非H5环境下，显示导出的数据供用户复制
    hideLoading()
    uni.showModal({
      title: '导出数据',
      content: '请复制以下数据并保存：\n' + (jsonData.length > 100 ? jsonData.slice(0, 100) + '...' : jsonData),
      showCancel: true,
      cancelText: '关闭',
      confirmText: '复制',
      success: (res) => {
        if (res.confirm) {
          uni.setClipboardData({
            data: jsonData,
            success: () => {
              uni.showToast({
                title: '已复制到剪贴板',
                icon: 'success'
              })
            }
          })
        }
      }
    })
    // #endif
  } catch (error) {
    hideLoading()
    uni.showModal({
      title: '导出失败',
      content: error.message || '导出过程中发生错误',
      showCancel: false
    })
  }
}

// 数据导入
const handleDataImport = async () => {
  try {
    // #ifdef H5
    // 在H5环境下，可以使用文件选择器
    uni.chooseFile({
      count: 1,
      type: 'file',
      extension: ['.json'],
      success: async (res) => {
        const file = res.tempFiles[0]
        
        // 读取文件内容
        const reader = new FileReader()
        reader.onload = async (e) => {
          try {
            showLoading('正在导入数据...')
            await backupService.restoreFromJson(e.target.result as string)
            hideLoading()
            
            uni.showToast({
              title: '导入成功',
              icon: 'success'
            })
          } catch (error) {
            hideLoading()
            uni.showModal({
              title: '导入失败',
              content: error.message || '导入过程中发生错误',
              showCancel: false
            })
          }
        }
        reader.readAsText(file)
      }
    })
    // #endif
    
    // #ifndef H5
    // 在非H5环境下，显示文本输入框供用户粘贴JSON数据
    uni.showModal({
      title: '导入数据',
      content: '请粘贴之前导出的JSON数据：',
      editable: true,
      success: async (res) => {
        if (res.confirm && res.content) {
          try {
            showLoading('正在导入数据...')
            await backupService.restoreFromJson(res.content)
            hideLoading()
            
            uni.showToast({
              title: '导入成功',
              icon: 'success'
            })
          } catch (error) {
            hideLoading()
            uni.showModal({
              title: '导入失败',
              content: error.message || '导入过程中发生错误',
              showCancel: false
            })
          }
        }
      }
    })
    // #endif
  } catch (error) {
    hideLoading()
    uni.showModal({
      title: '导入失败',
      content: error.message || '导入过程中发生错误',
      showCancel: false
    })
  }
}

// 清空数据
const handleClearData = async () => {
  uni.showModal({
    title: '警告',
    content: '确定要清空所有数据吗？此操作不可恢复！',
    confirmColor: '#FF0000',
    success: async (res) => {
      if (res.confirm) {
        try {
          showLoading('正在清空数据...')
          await backupService.restoreFromJson('{"version":1,"timestamp":"' + new Date().toISOString() + '","tasks":[]}')
          hideLoading()
          
          uni.showToast({
            title: '已清空数据',
            icon: 'success'
          })
        } catch (error) {
          hideLoading()
          uni.showModal({
            title: '操作失败',
            content: error.message || '清空数据过程中发生错误',
            showCancel: false
          })
        }
      }
    }
  })
}

// 显示加载中
const showLoading = (text: string = '加载中...') => {
  loadingText.value = text
  loading.value = true
}

// 隐藏加载中
const hideLoading = () => {
  loading.value = false
}

// 格式化日期为可用于文件名的字符串
const formatDate = (date: Date): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`
}

// 导航到测试数据管理页面
const navigateToTestDataPage = () => {
  uni.navigateTo({
    url: '/pages/dev/test-data',
  })
}

// 导航到数据库测试页面
const navigateToDatabaseTest = () => {
  uni.navigateTo({
    url: '/pages/task/database-test',
  })
}
</script>

<style lang="scss">
.settings-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f2f2f7;
}

.navbar {
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 16px;
  background-color: #ffffff;
}

.navbar-left {
  display: flex;
  align-items: center;
  width: 60px;
  font-size: 16px;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 17px;
  font-weight: 600;
}

.navbar-right {
  width: 60px;
  text-align: right;
}

.settings-container {
  flex: 1;
  width: 100%;
}

.settings-group {
  margin-bottom: 32px;
}

.settings-group-title {
  padding: 0 16px 8px;
  font-size: 13px;
  font-weight: 600;
  color: #8e8e93;
  text-transform: uppercase;
}

.settings-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background-color: #ffffff;
  border-top: 1px solid #e5e5ea;
}

.settings-item:first-child {
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  border-top: none;
}

.settings-item:last-child {
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}

.settings-item-left {
  display: flex;
  align-items: center;
}

.settings-item-label {
  margin-left: 12px;
  font-size: 16px;
}

.settings-item-right {
  display: flex;
  align-items: center;
}

.picker-text {
  font-size: 16px;
  color: #8e8e93;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.loading-content {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

.loading-text {
  font-size: 14px;
  color: #333;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 